package com.example.demo.tixiban;


/**
 * @author xujm
 * @version V2.4
 *
 * 单链表反转  反转后必须返回反转后的头结点，
 *
 * @since 2.4.0 2022/2/8 11:09
 */
public class List_单链表反转 {

    public static class Node {
        int val;
        Node next;
        Node(int x) { val = x; }
    }

    /**
     *   pre = null
     *   (1)
     *   1 ->   2   ->   3   ->  null
     *
     *   node
     *   head

     *   (2)
     * null<- 1    2   ->   3   ->  null
     *
     *        pre  head
     *             next
     *    next = head.next
     *    head.next = pre
     *    pre = head
     *    head = next
     *
     *  (3)
     *   null<- 1  <-  2      3   ->  null
     *                 pre   head
     *                       next
     *    next = head.next
     *    head.next = pre
     *    pre = head
     *    head = next
     *
     * @param head
     * @return
     */
    public static Node reverseNode(Node head){
            Node pre = null;
            Node next = null;
            while(head != null){
                next = head.next;
                head.next =  pre;
                pre = head;
                head = next;

            }
        return pre;
    }




    public static void main(String[] args) {

        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);

        Node newHead = reverseNode(head);
        while (newHead!=null){
            System.out.println(newHead.val);
            newHead = newHead.next;
        }
    }

}
